<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */

namespace App\Cache;

use App\Constants\CacheKey;
use App\Repository\AddressRepository;


class AddressCache extends BaseHashCache
{
    public static $cacheKey = CacheKey::MEMBER_ADDRESS;

    /**
     * Notes:下单获取地址
     * @param $member_id
     * @param int $id
     * @return array|mixed
     */
    public function getAddress($member_id, int $id = 0)
    {
        if (empty($id)) {
            return $this->getDefault($member_id);
        }
        $address = $this->get($member_id);
        return $address[$id] ?? null;
    }

    /**
     * Notes:获取默认收货地址
     * User: pace
     * Date: 2021/02/02
     * @return array
     */
    public function getDefault($member_id): ?array
    {
        $data = $this->get($member_id);
        foreach ($data as $value) {
            if ($value['is_default'] == 1) {
                return $value;
            }
        }
        return null;
    }

    /**
     * 从模型中加载
     * @param string $key  主键key
     * @return array
     */
    public function loadFromModel($key): ?array
    {
        $address = AddressRepository::getInstance()->getRows(['member_id' => $key]);

        return !empty($address) ? $address : null;
    }

    /**
     * 检查数据并格式化
     * @param $data
     * @return array
     */
    public function formatDataFromModel($data) : array
    {
        return array_column($data,null,'id');
    }

}
